package cn.edu.sziit.bbs.service;

import cn.edu.sziit.bbs.dao.UserMapper;

import cn.edu.sziit.bbs.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 插入user
     *
     * @param user
     */
    public void insert(User user) {
        userMapper.insertSelective(user);
    }

    /**
     * 根据用户名字查询用户
     *
     * @param userName
     * @return
     */
    public User selectByUsername(String userName) {
        return userMapper.selectByUsername(userName);
    }

    /**
     * 检测登录用户
     *
     * @param user
     * @return
     */
    public String userCheck(User user) {
        if (user.getUserName().equals("")) {
            return "用户名不能为空";
        } else if (user.getUserPassword().equals("")) {
            return "密码不能为空";
        }

        User user1 = userMapper.selectByUsername(user.getUserName());
        if (user1 == null) {
            return "用户名不存在";
        }

        String userPassword = user1.getUserPassword();

        if (userPassword.equals(user.getUserPassword())) {
            if (user1.getUserLevel().equals("admin")) {
                return "管理员登陆成功";
            }
            return "登录成功";
        }
        return "密码错误";

    }

    /**
     * 根据用户id删除帐号
     *
     * @param userId
     * @return
     */
    public String deleteByPrimaryKey(Integer userId) {
        userMapper.deleteByPrimaryKey(userId);
        return "删除用户成功";
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    /**
     * 更新用户
     *
     * @param user
     * @return
     */
    public String updateByPrimaryKeySelective(User user) {
        userMapper.updateByPrimaryKeySelective(user);
        return "更新用户成功";
    }

    /**
     * 根据userName模糊查询user
     *
     * @param userName
     * @return
     */
    public List<User> selectAllByUserName(String userName) {
        return userMapper.selectAllByUserName(userName);
    }

    public String checkRegister(User user, String userPassword2, String code, HttpSession session) {

        if (!code.equals(session.getAttribute("randomString"))) {
            System.out.println(code);
            System.out.println(session.getAttribute("randomString"));
            System.out.println("验证码错误");

            return "验证码错误";
        }
        if (!userPassword2.equals(user.getUserPassword())) {
            System.out.println("两次的密码不一致");

            return "两次的密码不一致";
        }
        if (userMapper.selectByUsername(user.getUserName()) != null) {
            return user.getUserName() + "用户名已经存在";
        }
        return "注册成功";
    }

}
